package api

import (
	"TaskAssignmentSystem/internal/admin/dao"
	adminServices "TaskAssignmentSystem/internal/admin/services"
	"TaskAssignmentSystem/internal/pkg/middleware/handler"
	"TaskAssignmentSystem/pkg/oss"
	"TaskAssignmentSystem/pkg/timehandler"
	"TaskAssignmentSystem/pkg/utils"
	"errors"
	"fmt"
	"github.com/go-the-way/exl"
	"github.com/kataras/iris/v12"
	"io/ioutil"
	"os"
	"strings"
	"time"
)

type OrderCashRequest struct {
	ProductId      string  `json:"product_id"`
	Balance        float64 `json:"balance"`
	TotalAmount    float64 `json:"total_amount"`
	TaxAmount      float64 `json:"tax_amount"`
	ReceivedAmount float64 `json:"received_amount"`
	Remark         string  `json:"remark"`
}

func OrderCashHandler(ctx iris.Context) {
	var RequestParams OrderCashRequest
	if err := ctx.ReadJSON(&RequestParams); err != nil {
		handler.ArgumentErrorHandle(err, ctx)
		return
	}
	//判断权限
	var claims adminServices.CustomClaims
	if err := claims.ParseClaims(ctx); err != nil {
		ctx.JSON(utils.ResponseError{Code: iris.StatusInternalServerError, Message: err.Error()})
		return
	}
	//判断是否实名
	var userDao dao.Common[dao.SystemUser]
	if user, err := userDao.First(map[string]interface{}{"id": claims.Id}); err != nil {
		ctx.JSON(utils.ResponseError{Code: iris.StatusInternalServerError, Message: err.Error()})
		return
	} else {
		if utils.StringIsEmpty(user.Phone) || utils.StringIsEmpty(user.Email) || utils.StringIsEmpty(user.AlipayAccount) {
			ctx.JSON(utils.ResponseError{Code: iris.StatusInternalServerError, Message: "依据国家劳务报酬所得税报税要求以及提现条件，需先完成实名认证并填写手机号、邮箱、支付宝号码后才能进行提现"})
			return
		}
	}
	var serve adminServices.SystemOrderService
	var param = make(map[string]string)
	param["order_type"] = adminServices.OrderTypeCashStr
	param["product_id"] = RequestParams.ProductId
	param["balance"] = utils.Float64ToString(RequestParams.Balance)
	param["total_amount"] = utils.Float64ToString(RequestParams.TotalAmount)
	param["tax_amount"] = utils.Float64ToString(RequestParams.TaxAmount)
	param["received_amount"] = utils.Float64ToString(RequestParams.ReceivedAmount)
	param["remark"] = RequestParams.Remark
	if orderId, err := serve.OrderCreate(claims.Id, param); err != nil {
		ctx.JSON(utils.ResponseServerError(err))
		return
	} else {
		ctx.JSON(utils.ResponseData(iris.Map{"orderId": orderId}))
		return
	}
}

type OrderProductRequest struct {
	ProductId string  `json:"product_id"`
	Balance   float64 `json:"balance"`
	Number    int     `json:"number"`
	Remark    string  `json:"remark"`
}

func OrderProductHandler(ctx iris.Context) {
	var RequestParams OrderProductRequest
	if err := ctx.ReadJSON(&RequestParams); err != nil {
		handler.ArgumentErrorHandle(err, ctx)
		return
	}
	//判断权限
	var claims adminServices.CustomClaims
	if err := claims.ParseClaims(ctx); err != nil {
		ctx.JSON(utils.ResponseError{Code: iris.StatusInternalServerError, Message: err.Error()})
		return
	}
	//判断是否实名
	var userDao dao.Common[dao.SystemUser]
	if user, err := userDao.First(map[string]interface{}{"id": claims.Id}); err != nil {
		ctx.JSON(utils.ResponseError{Code: iris.StatusInternalServerError, Message: err.Error()})
		return
	} else {
		if utils.StringIsEmpty(user.Phone) || utils.StringIsEmpty(user.Email) || utils.StringIsEmpty(user.DeliveryAddress) {
			ctx.JSON(utils.ResponseError{Code: iris.StatusInternalServerError, Message: "依据兑换条件，需先完成账号手机号、邮箱、收货地址填写后才能进行兑换"})
			return
		}
	}
	var serve adminServices.SystemOrderService
	var param = make(map[string]string)
	param["order_type"] = adminServices.OrderTypeProductStr
	param["product_id"] = RequestParams.ProductId
	param["balance"] = utils.Float64ToString(RequestParams.Balance)
	param["number"] = utils.IntToString(RequestParams.Number)
	param["remark"] = RequestParams.Remark
	if orderId, err := serve.OrderCreate(claims.Id, param); err != nil {
		ctx.JSON(utils.ResponseServerError(err))
		return
	} else {
		ctx.JSON(utils.ResponseData(iris.Map{"orderId": orderId}))
		return
	}
}

type OrderQueryRequest struct {
	Page           int64  `json:"page"`
	PageSize       int64  `json:"page_size"`
	Status         string `json:"status"`
	Name           string `json:"name"`
	UserId         string `json:"user_id"`
	TeamNumber     string `json:"team_number"`
	ApplyTimeStart string `json:"apply_time_start"`
	ApplyTimeEnd   string `json:"apply_time_end"`
	ApplyAmount    string `json:"apply_amount"`
	ProductName    string `json:"product_name"`
	AlipayAccount  string `json:"alipay_account"`
	UserIds        string `json:"user_ids"`
	OrderIds       string `json:"order_ids"`
	OrderId        string `json:"order_id"`
}

func OrderReviewRecordsHandler(ctx iris.Context) {
	var RequestParams OrderQueryRequest
	if err := ctx.ReadJSON(&RequestParams); err != nil {
		handler.ArgumentErrorHandle(err, ctx)
		return
	}
	//判断权限
	var claims adminServices.CustomClaims
	if err := claims.ParseClaims(ctx); err != nil {
		ctx.JSON(utils.ResponseError{Code: iris.StatusInternalServerError, Message: err.Error()})
		return
	}
	var serve adminServices.SystemOrderService
	var param = make(map[string]string)
	if utils.StringIsNotEmpty(RequestParams.Status) {
		param["status"] = RequestParams.Status
	}
	if total, list, err := serve.OrderReviewRecordList(claims.Id, RequestParams.Page, RequestParams.PageSize, param); err != nil {
		ctx.JSON(utils.ResponseServerError(err))
		return
	} else {
		ctx.JSON(utils.ResponseData(iris.Map{"count": total, "list": list}))
		return
	}
}

func AdminCashOrderReviewRecordsHandler(ctx iris.Context) {
	var RequestParams OrderQueryRequest
	if err := ctx.ReadJSON(&RequestParams); err != nil {
		handler.ArgumentErrorHandle(err, ctx)
		return
	}
	//判断权限
	var claims adminServices.CustomClaims
	if err := claims.ParseClaims(ctx); err != nil {
		ctx.JSON(utils.ResponseError{Code: iris.StatusInternalServerError, Message: err.Error()})
		return
	}
	var serve adminServices.SystemOrderService
	var param = make(map[string]string)
	param["query_type"] = "cash"
	if utils.StringIsNotEmpty(RequestParams.Status) {
		param["status"] = RequestParams.Status
	}
	if utils.StringIsNotEmpty(RequestParams.Name) {
		param["name"] = RequestParams.Name
	}
	if utils.StringIsNotEmpty(RequestParams.UserId) {
		param["user_id"] = RequestParams.UserId
	}
	if utils.StringIsNotEmpty(RequestParams.TeamNumber) {
		param["team_number"] = RequestParams.TeamNumber
	}
	if utils.StringIsNotEmpty(RequestParams.ApplyTimeStart) {
		param["apply_time_start"] = RequestParams.ApplyTimeStart
	}
	if utils.StringIsNotEmpty(RequestParams.ApplyTimeEnd) {
		param["apply_time_end"] = RequestParams.ApplyTimeEnd
	}
	if utils.StringIsNotEmpty(RequestParams.ApplyAmount) {
		param["apply_amount"] = RequestParams.ApplyAmount
	}
	if utils.StringIsNotEmpty(RequestParams.AlipayAccount) {
		param["alipay_account"] = RequestParams.AlipayAccount
	}
	if utils.StringIsNotEmpty(RequestParams.OrderId) {
		param["order_id"] = RequestParams.OrderId
	}
	if total, list, err := serve.AdminOrderReviewRecordList(claims.Id, RequestParams.Page, RequestParams.PageSize, param); err != nil {
		ctx.JSON(utils.ResponseServerError(err))
		return
	} else {
		ctx.JSON(utils.ResponseData(iris.Map{"count": total, "list": list}))
		return
	}
}

func AdminProductOrderReviewRecordsHandler(ctx iris.Context) {
	var RequestParams OrderQueryRequest
	if err := ctx.ReadJSON(&RequestParams); err != nil {
		handler.ArgumentErrorHandle(err, ctx)
		return
	}
	//判断权限
	var claims adminServices.CustomClaims
	if err := claims.ParseClaims(ctx); err != nil {
		ctx.JSON(utils.ResponseError{Code: iris.StatusInternalServerError, Message: err.Error()})
		return
	}
	var serve adminServices.SystemOrderService
	var param = make(map[string]string)
	param["query_type"] = "product"
	if utils.StringIsNotEmpty(RequestParams.Status) {
		param["status"] = RequestParams.Status
	}
	if utils.StringIsNotEmpty(RequestParams.Name) {
		param["name"] = RequestParams.Name
	}
	if utils.StringIsNotEmpty(RequestParams.UserId) {
		param["user_id"] = RequestParams.UserId
	}
	if utils.StringIsNotEmpty(RequestParams.TeamNumber) {
		param["team_number"] = RequestParams.TeamNumber
	}
	if utils.StringIsNotEmpty(RequestParams.ApplyTimeStart) {
		param["apply_time_start"] = RequestParams.ApplyTimeStart
	}
	if utils.StringIsNotEmpty(RequestParams.ApplyTimeEnd) {
		param["apply_time_end"] = RequestParams.ApplyTimeEnd
	}
	if utils.StringIsNotEmpty(RequestParams.ProductName) {
		param["product_name"] = RequestParams.ProductName
	}
	if utils.StringIsNotEmpty(RequestParams.AlipayAccount) {
		param["alipay_account"] = RequestParams.AlipayAccount
	}
	if utils.StringIsNotEmpty(RequestParams.OrderId) {
		param["order_id"] = RequestParams.OrderId
	}
	if total, list, err := serve.AdminOrderReviewRecordList(claims.Id, RequestParams.Page, RequestParams.PageSize, param); err != nil {
		ctx.JSON(utils.ResponseServerError(err))
		return
	} else {
		ctx.JSON(utils.ResponseData(iris.Map{"count": total, "list": list}))
		return
	}
}

type ApprovalAndRejection struct {
	OrderId       string `json:"order_id"`       //订单号
	ReviewDesc    string `json:"review_desc"`    //审核说明
	ReviewDetails string `json:"review_details"` //审核详情说明
}

func AdminOrderApprovalHandler(ctx iris.Context) {
	var RequestParams ApprovalAndRejection
	if err := ctx.ReadJSON(&RequestParams); err != nil {
		handler.ArgumentErrorHandle(err, ctx)
		return
	}
	//判断权限
	var claims adminServices.CustomClaims
	if err := claims.ParseClaims(ctx); err != nil {
		ctx.JSON(utils.ResponseError{Code: iris.StatusInternalServerError, Message: err.Error()})
		return
	}
	var serve adminServices.SystemOrderService
	var param = make(map[string]string)
	param["up_type"] = "approval"
	param["order_id"] = RequestParams.OrderId
	param["review_desc"] = RequestParams.ReviewDesc
	if err := serve.AdminEditOrderReviewRecord(claims.Id, param); err != nil {
		ctx.JSON(utils.ResponseServerError(err))
		return
	} else {
		ctx.JSON(utils.ResponseOK())
		return
	}
}

func AdminOrderRejectionHandler(ctx iris.Context) {
	var RequestParams ApprovalAndRejection
	if err := ctx.ReadJSON(&RequestParams); err != nil {
		handler.ArgumentErrorHandle(err, ctx)
		return
	}
	//判断权限
	var claims adminServices.CustomClaims
	if err := claims.ParseClaims(ctx); err != nil {
		ctx.JSON(utils.ResponseError{Code: iris.StatusInternalServerError, Message: err.Error()})
		return
	}
	var serve adminServices.SystemOrderService
	var param = make(map[string]string)
	param["up_type"] = "rejection"
	param["order_id"] = RequestParams.OrderId
	param["review_desc"] = RequestParams.ReviewDesc
	if err := serve.AdminEditOrderReviewRecord(claims.Id, param); err != nil {
		ctx.JSON(utils.ResponseServerError(err))
		return
	} else {
		ctx.JSON(utils.ResponseOK())
		return
	}
}

func AdminOrderReviewDetailsHandler(ctx iris.Context) {
	var RequestParams ApprovalAndRejection
	if err := ctx.ReadJSON(&RequestParams); err != nil {
		handler.ArgumentErrorHandle(err, ctx)
		return
	}
	//判断权限
	var claims adminServices.CustomClaims
	if err := claims.ParseClaims(ctx); err != nil {
		ctx.JSON(utils.ResponseError{Code: iris.StatusInternalServerError, Message: err.Error()})
		return
	}
	var serve adminServices.SystemOrderService
	var param = make(map[string]string)
	param["up_type"] = "review_details"
	param["order_id"] = RequestParams.OrderId
	param["review_desc"] = RequestParams.ReviewDesc
	param["review_details"] = RequestParams.ReviewDetails
	if err := serve.AdminEditOrderReviewRecord(claims.Id, param); err != nil {
		ctx.JSON(utils.ResponseServerError(err))
		return
	} else {
		ctx.JSON(utils.ResponseOK())
		return
	}
}

type ExportCashReviewRecords struct {
	ApplyTime      string  `excel:"申请时间"`
	OrderId        string  `excel:"订单号"`
	AlipayAccount  string  `excel:"支付宝账号"`
	Name           string  `excel:"用户姓名"`
	ReceivedAmount float64 `excel:"实际到账金额"`
	TaxAmount      float64 `excel:"纳税金额"`
	Number         float64 `excel:"申请提现金额"`
	Balance        float64 `excel:"芝草扣除"`
	Remark         string  `excel:"申请备注"`
	NickName       string  `excel:"用户昵称"`
	UserId         string  `excel:"用户ID"`
	IdCardNumber   string  `excel:"用户身份证号"`
	Phone          string  `excel:"用户手机号"`
	Email          string  `excel:"用户邮箱"`
	TeamNumber     string  `excel:"用户所属团队"`
	TeamUserName   string  `excel:"团长姓名"`
	TlNickName     string  `excel:"团长昵称"`
	TeamUserId     string  `excel:"团长用户ID"`
	TlPhone        string  `excel:"团长手机号"`
	TlEmail        string  `excel:"团长用户邮箱"`
	ReviewDesc     string  `excel:"审核结果"`
	//ReviewDetail       string  `excel:"审核详情"`
	AlipayPayTime      string `excel:"支付宝实际支付时间（选填）"`
	AlipayOrderNo      string `excel:"支付宝订单号（选填）"`
	AlipaySerialNumber string `excel:"支付宝流水号（选填）"`
	PayAccount         string `excel:"收款账号（选填）"`
	PayName            string `excel:"姓名（选填）"`
	Amount             string `excel:"金额（元）（选填）"`
	Status             string `excel:"状态（选填）"`
	PayRemark          string `excel:"备注（选填）"`
	FailReason         string `excel:"失败原因（选填）"`
	Text               string `excel:"提示文本"`
}

func (m *ExportCashReviewRecords) Configure(wc *exl.WriteConfig) {}

func ExportCashReviewRecordsHandler(ctx iris.Context) {
	var RequestParams OrderQueryRequest
	if err := ctx.ReadJSON(&RequestParams); err != nil {
		handler.ArgumentErrorHandle(err, ctx)
		return
	}
	//判断权限
	var claims adminServices.CustomClaims
	if err := claims.ParseClaims(ctx); err != nil {
		ctx.JSON(utils.ResponseError{Code: iris.StatusInternalServerError, Message: err.Error()})
		return
	}
	var serve adminServices.SystemOrderService
	var param = make(map[string]string)
	param["query_type"] = "cash"
	if utils.StringIsNotEmpty(RequestParams.Status) {
		param["status"] = RequestParams.Status
	}
	if utils.StringIsNotEmpty(RequestParams.Name) {
		param["name"] = RequestParams.Name
	}
	if utils.StringIsNotEmpty(RequestParams.UserId) {
		param["user_id"] = RequestParams.UserId
	}
	if utils.StringIsNotEmpty(RequestParams.TeamNumber) {
		param["team_number"] = RequestParams.TeamNumber
	}
	if utils.StringIsNotEmpty(RequestParams.ApplyTimeStart) {
		param["apply_time_start"] = RequestParams.ApplyTimeStart
	}
	if utils.StringIsNotEmpty(RequestParams.ApplyTimeEnd) {
		param["apply_time_end"] = RequestParams.ApplyTimeEnd
	}
	if utils.StringIsNotEmpty(RequestParams.ApplyAmount) {
		param["apply_amount"] = RequestParams.ApplyAmount
	}
	if utils.StringIsNotEmpty(RequestParams.AlipayAccount) {
		param["alipay_account"] = RequestParams.AlipayAccount
	}
	if utils.StringIsNotEmpty(RequestParams.OrderId) {
		param["order_id"] = RequestParams.OrderId
	}
	ExportData, err := serve.ExportOrderReviewRecordList(claims.Id, param)
	if err != nil {
		ctx.JSON(utils.ResponseError{Code: iris.StatusInternalServerError, Message: err.Error()})
		return
	}
	index := 0
	exportCashReviewRecords := make([]*ExportCashReviewRecords, len(ExportData))
	for _, model := range ExportData {
		exportCashReviewRecords[index] = &ExportCashReviewRecords{}
		exportCashReviewRecords[index].ApplyTime = model.ApplyTime.Format(timehandler.FormatLayoutTime)
		exportCashReviewRecords[index].OrderId = model.OrderId
		exportCashReviewRecords[index].AlipayAccount = model.AlipayAccount
		exportCashReviewRecords[index].Name = model.Name
		exportCashReviewRecords[index].ReceivedAmount = model.ReceivedAmount
		exportCashReviewRecords[index].TaxAmount = model.TaxAmount
		exportCashReviewRecords[index].Number = model.TotalAmount
		exportCashReviewRecords[index].Balance = model.Balance
		exportCashReviewRecords[index].Remark = model.Remark
		exportCashReviewRecords[index].NickName = model.NickName
		exportCashReviewRecords[index].UserId = model.UserId
		exportCashReviewRecords[index].IdCardNumber = model.IdCardNumber
		exportCashReviewRecords[index].Phone = model.Phone
		exportCashReviewRecords[index].Email = model.Email
		exportCashReviewRecords[index].TeamNumber = model.TeamNumber
		exportCashReviewRecords[index].TeamUserName = model.TeamUserName
		exportCashReviewRecords[index].TlNickName = model.TlNickName
		exportCashReviewRecords[index].TeamUserId = model.TeamUserId
		exportCashReviewRecords[index].TlPhone = model.TlPhone
		exportCashReviewRecords[index].TlEmail = model.TlEmail

		reviewDetail := model.ReviewDetails
		reviewDetailList := strings.Split(reviewDetail, ",")
		for i, r := range reviewDetailList {
			in := strings.Index(r, ":")
			switch i {
			case 0:
				exportCashReviewRecords[index].AlipayPayTime = r[in+1:]
			case 1:
				exportCashReviewRecords[index].AlipayOrderNo = r[in+1:]
			case 2:
				exportCashReviewRecords[index].AlipaySerialNumber = r[in+1:]
			case 3:
				exportCashReviewRecords[index].PayAccount = r[in+1:]
			case 4:
				exportCashReviewRecords[index].PayName = r[in+1:]
			case 5:
				exportCashReviewRecords[index].Amount = r[in+1:]
			case 6:
				exportCashReviewRecords[index].Status = r[in+1:]
			case 7:
				exportCashReviewRecords[index].PayRemark = r[in+1:]
			case 8:
				exportCashReviewRecords[index].FailReason = r[in+1:]
			}
		}
		/*exportCashReviewRecords[index].AlipayPayTime = ""
		exportCashReviewRecords[index].AlipayOrderNo = ""
		exportCashReviewRecords[index].AlipaySerialNumber = ""
		exportCashReviewRecords[index].PayAccount = ""
		exportCashReviewRecords[index].PayName = ""
		exportCashReviewRecords[index].Amount = ""
		exportCashReviewRecords[index].Status = ""
		exportCashReviewRecords[index].PayRemark = ""
		exportCashReviewRecords[index].FailReason = ""*/
		exportCashReviewRecords[index].Text = model.ReviewDesc
		//exportCashReviewRecords[index].ReviewDetail = model.ReviewDetails
		if model.Status == 0 {
			exportCashReviewRecords[index].ReviewDesc = "审核中"
		} else if model.Status == 1 {
			exportCashReviewRecords[index].ReviewDesc = "已通过"
		} else if model.Status == 2 {
			exportCashReviewRecords[index].ReviewDesc = "审核不通过"
		}
		index++
	}
	unix := time.Now().UnixNano()
	if err := exl.Write(fmt.Sprintf("./export/export_cash_review_records_%d.xlsx", unix), exportCashReviewRecords); err != nil {
		fmt.Println("write excel err:" + err.Error())
		return
	}
	tempFilename := fmt.Sprintf("./export/export_cash_review_records_%d.xlsx", unix)
	//删除本地临时文件
	defer os.Remove(tempFilename)
	bucketClient := oss.BucketClient{}
	readFile, _ := ioutil.ReadFile(fmt.Sprintf("./export/export_cash_review_records_%d.xlsx", unix))
	bucketClient.UpBytes(readFile, fmt.Sprintf("task-assign/order/export/export_cash_review_records_%d.xlsx", unix))
	ctx.JSON(utils.Response{Code: iris.StatusOK, Message: iris.StatusText(iris.StatusOK), Data: fmt.Sprintf("%s/task-assign/order/export/export_cash_review_records_%d.xlsx", utils.ServerConf.AliOssConf.CallBackHost, unix)})
	return
}

type ExportProductReviewRecords struct {
	ApplyTime       string  `excel:"申请时间"`
	OrderId         string  `excel:"订单号"`
	Name            string  `excel:"用户姓名"`
	ProductName     string  `excel:"申请兑换物品名称"`
	Number          int     `excel:"申请数量"`
	Balance         float64 `excel:"芝草扣除"`
	Remark          string  `excel:"申请备注"`
	NickName        string  `excel:"用户昵称"`
	DeliveryAddress string  `excel:"地址"`
	UserId          string  `excel:"用户ID"`
	IdCardNumber    string  `excel:"用户身份证号"`
	Phone           string  `excel:"用户手机号"`
	Email           string  `excel:"用户邮箱"`
	TeamNumber      string  `excel:"用户所属团队"`
	TeamUserName    string  `excel:"团长姓名"`
	TlNickName      string  `excel:"团长昵称"`
	TeamUserId      string  `excel:"团长用户ID"`
	TlPhone         string  `excel:"团长手机号"`
	TlEmail         string  `excel:"团长用户邮箱"`
	ReviewDesc      string  `excel:"审核结果"`
	//ReviewDetail    string  `excel:"审核详情"`
	DeliveryTime   string `excel:"发货时间（选填）"`
	TrackingNumber string `excel:"运单号（选填）"`
	SendingCompany string `excel:"寄件公司（选填）"`
	PayRemark      string `excel:"备注（选填）"`
	Text           string `excel:"提示文本"`
}

func (m *ExportProductReviewRecords) Configure(wc *exl.WriteConfig) {}

func ExportProductReviewRecordsHandler(ctx iris.Context) {
	var RequestParams OrderQueryRequest
	if err := ctx.ReadJSON(&RequestParams); err != nil {
		handler.ArgumentErrorHandle(err, ctx)
		return
	}
	//判断权限
	var claims adminServices.CustomClaims
	if err := claims.ParseClaims(ctx); err != nil {
		ctx.JSON(utils.ResponseError{Code: iris.StatusInternalServerError, Message: err.Error()})
		return
	}
	var serve adminServices.SystemOrderService
	var param = make(map[string]string)
	param["query_type"] = "product"
	if utils.StringIsNotEmpty(RequestParams.Status) {
		param["status"] = RequestParams.Status
	}
	if utils.StringIsNotEmpty(RequestParams.Name) {
		param["name"] = RequestParams.Name
	}
	if utils.StringIsNotEmpty(RequestParams.UserId) {
		param["user_id"] = RequestParams.UserId
	}
	if utils.StringIsNotEmpty(RequestParams.TeamNumber) {
		param["team_number"] = RequestParams.TeamNumber
	}
	if utils.StringIsNotEmpty(RequestParams.ApplyTimeStart) {
		param["apply_time_start"] = RequestParams.ApplyTimeStart
	}
	if utils.StringIsNotEmpty(RequestParams.ApplyTimeEnd) {
		param["apply_time_end"] = RequestParams.ApplyTimeEnd
	}
	if utils.StringIsNotEmpty(RequestParams.ApplyAmount) {
		param["apply_amount"] = RequestParams.ApplyAmount
	}
	if utils.StringIsNotEmpty(RequestParams.AlipayAccount) {
		param["alipay_account"] = RequestParams.AlipayAccount
	}
	if utils.StringIsNotEmpty(RequestParams.OrderIds) {
		param["order_ids"] = RequestParams.OrderIds
	}
	ExportData, err := serve.ExportOrderReviewRecordList(claims.Id, param)
	if err != nil {
		ctx.JSON(utils.ResponseError{Code: iris.StatusInternalServerError, Message: err.Error()})
		return
	}
	index := 0
	exportProductReviewRecords := make([]*ExportProductReviewRecords, len(ExportData))
	for _, model := range ExportData {
		exportProductReviewRecords[index] = &ExportProductReviewRecords{}
		exportProductReviewRecords[index].ApplyTime = model.ApplyTime.Format(timehandler.FormatLayoutTime)
		exportProductReviewRecords[index].OrderId = model.OrderId
		exportProductReviewRecords[index].Name = model.Name
		exportProductReviewRecords[index].ProductName = model.ProductName
		exportProductReviewRecords[index].Number = model.Number
		exportProductReviewRecords[index].Balance = model.Balance
		exportProductReviewRecords[index].Remark = model.Remark
		exportProductReviewRecords[index].NickName = model.NickName
		exportProductReviewRecords[index].DeliveryAddress = model.DeliveryAddress
		exportProductReviewRecords[index].UserId = model.UserId
		exportProductReviewRecords[index].IdCardNumber = model.IdCardNumber
		exportProductReviewRecords[index].Phone = model.Phone
		exportProductReviewRecords[index].Email = model.Email
		exportProductReviewRecords[index].TeamNumber = model.TeamNumber
		exportProductReviewRecords[index].TeamUserName = model.TeamUserName
		exportProductReviewRecords[index].TlNickName = model.TlNickName
		exportProductReviewRecords[index].TeamUserId = model.TeamUserId
		exportProductReviewRecords[index].TlPhone = model.TlPhone
		exportProductReviewRecords[index].TlEmail = model.TlEmail

		reviewDetail := model.ReviewDetails
		reviewDetailList := strings.Split(reviewDetail, ",")
		for i, r := range reviewDetailList {
			in := strings.Index(r, ":")
			switch i {
			case 0:
				exportProductReviewRecords[index].DeliveryTime = r[in+1:]
			case 1:
				exportProductReviewRecords[index].TrackingNumber = r[in+1:]
			case 2:
				exportProductReviewRecords[index].SendingCompany = r[in+1:]
			case 3:
				exportProductReviewRecords[index].PayRemark = r[in+1:]
			}
		}
		/*exportProductReviewRecords[index].DeliveryTime = ""
		exportProductReviewRecords[index].TrackingNumber = ""
		exportProductReviewRecords[index].SendingCompany = ""
		exportProductReviewRecords[index].PayRemark = ""*/
		exportProductReviewRecords[index].Text = model.ReviewDesc
		//exportProductReviewRecords[index].ReviewDetail = model.ReviewDetails
		if model.Status == 0 {
			exportProductReviewRecords[index].ReviewDesc = "审核中"
		} else if model.Status == 1 {
			exportProductReviewRecords[index].ReviewDesc = "已通过"
		} else if model.Status == 2 {
			exportProductReviewRecords[index].ReviewDesc = "审核不通过"
		}
		index++
	}
	unix := time.Now().UnixNano()
	if err := exl.Write(fmt.Sprintf("./export/export_product_review_records_%d.xlsx", unix), exportProductReviewRecords); err != nil {
		fmt.Println("write excel err:" + err.Error())
		return
	}
	tempFilename := fmt.Sprintf("./export/export_product_review_records_%d.xlsx", unix)
	//删除本地临时文件
	defer os.Remove(tempFilename)
	bucketClient := oss.BucketClient{}
	readFile, _ := ioutil.ReadFile(fmt.Sprintf("./export/export_product_review_records_%d.xlsx", unix))
	bucketClient.UpBytes(readFile, fmt.Sprintf("task-assign/order/export/export_product_review_records_%d.xlsx", unix))
	ctx.JSON(utils.Response{Code: iris.StatusOK, Message: iris.StatusText(iris.StatusOK), Data: fmt.Sprintf("%s/task-assign/order/export/export_product_review_records_%d.xlsx", utils.ServerConf.AliOssConf.CallBackHost, unix)})
	return
}

type ExportCashReviewRecordsAllSelect struct {
	ApplyTime          string  `excel:"申请时间"`
	OrderId            string  `excel:"订单号"`
	AlipayAccount      string  `excel:"支付宝账号"`
	Name               string  `excel:"用户姓名"`
	ReceivedAmount     float64 `excel:"实际到账金额"`
	TaxAmount          float64 `excel:"纳税金额"`
	Number             float64 `excel:"申请提现金额"`
	Balance            float64 `excel:"芝草扣除"`
	Remark             string  `excel:"申请备注"`
	NickName           string  `excel:"用户昵称"`
	UserId             string  `excel:"用户ID"`
	IdCardNumber       string  `excel:"用户身份证号"`
	Phone              string  `excel:"用户手机号"`
	Email              string  `excel:"用户邮箱"`
	TeamNumber         string  `excel:"用户所属团队"`
	TeamUserName       string  `excel:"团长姓名"`
	TlNickName         string  `excel:"团长昵称"`
	TeamUserId         string  `excel:"团长用户ID"`
	TlPhone            string  `excel:"团长手机号"`
	TlEmail            string  `excel:"团长用户邮箱"`
	ReviewDesc         string  `excel:"审核详情"`
	AlipayPayTime      string  `excel:"支付宝实际支付时间（选填）"`
	AlipayOrderNo      string  `excel:"支付宝订单号（选填）"`
	AlipaySerialNumber string  `excel:"支付宝流水号（选填）"`
	PayAccount         string  `excel:"收款账号（选填）"`
	PayName            string  `excel:"姓名（选填）"`
	Amount             string  `excel:"金额（元）（选填）"`
	Status             string  `excel:"状态（选填）"`
	PayRemark          string  `excel:"备注（选填）"`
	FailReason         string  `excel:"失败原因（选填）"`
	Text               string  `excel:"提示文本"`
}

func (m *ExportCashReviewRecordsAllSelect) Configure(wc *exl.WriteConfig) {}

func ExportCashReviewRecordsAllSelectHandler(ctx iris.Context) {
	var RequestParams OrderQueryRequest
	if err := ctx.ReadJSON(&RequestParams); err != nil {
		handler.ArgumentErrorHandle(err, ctx)
		return
	}
	//判断权限
	var claims adminServices.CustomClaims
	if err := claims.ParseClaims(ctx); err != nil {
		ctx.JSON(utils.ResponseError{Code: iris.StatusInternalServerError, Message: err.Error()})
		return
	}
	var serve adminServices.SystemOrderService
	var param = make(map[string]string)
	param["query_type"] = "cash"
	if utils.StringIsNotEmpty(RequestParams.Status) {
		param["status"] = RequestParams.Status
	}
	if utils.StringIsNotEmpty(RequestParams.Name) {
		param["name"] = RequestParams.Name
	}
	if utils.StringIsNotEmpty(RequestParams.UserId) {
		param["user_id"] = RequestParams.UserId
	}
	if utils.StringIsNotEmpty(RequestParams.TeamNumber) {
		param["team_number"] = RequestParams.TeamNumber
	}
	if utils.StringIsNotEmpty(RequestParams.ApplyTimeStart) {
		param["apply_time_start"] = RequestParams.ApplyTimeStart
	}
	if utils.StringIsNotEmpty(RequestParams.ApplyTimeEnd) {
		param["apply_time_end"] = RequestParams.ApplyTimeEnd
	}
	if utils.StringIsNotEmpty(RequestParams.ApplyAmount) {
		param["apply_amount"] = RequestParams.ApplyAmount
	}
	if utils.StringIsNotEmpty(RequestParams.AlipayAccount) {
		param["alipay_account"] = RequestParams.AlipayAccount
	}
	if utils.StringIsNotEmpty(RequestParams.UserIds) {
		param["user_ids"] = RequestParams.UserIds
	}
	ExportData, err := serve.ExportOrderReviewRecordList(claims.Id, param)
	if err != nil {
		ctx.JSON(utils.ResponseError{Code: iris.StatusInternalServerError, Message: err.Error()})
		return
	}
	index := 0
	exportCashReviewRecords := make([]*ExportCashReviewRecordsAllSelect, len(ExportData))
	for _, model := range ExportData {
		exportCashReviewRecords[index] = &ExportCashReviewRecordsAllSelect{}
		exportCashReviewRecords[index].ApplyTime = model.ApplyTime.Format(timehandler.FormatLayoutTime)
		exportCashReviewRecords[index].OrderId = model.OrderId
		exportCashReviewRecords[index].AlipayAccount = model.AlipayAccount
		exportCashReviewRecords[index].Name = model.Name
		exportCashReviewRecords[index].ReceivedAmount = model.ReceivedAmount
		exportCashReviewRecords[index].TaxAmount = model.TaxAmount
		exportCashReviewRecords[index].Number = model.TotalAmount
		exportCashReviewRecords[index].Balance = model.Balance
		exportCashReviewRecords[index].Remark = model.Remark
		exportCashReviewRecords[index].NickName = model.NickName
		exportCashReviewRecords[index].UserId = model.UserId
		exportCashReviewRecords[index].IdCardNumber = model.IdCardNumber
		exportCashReviewRecords[index].Phone = model.Phone
		exportCashReviewRecords[index].Email = model.Email
		exportCashReviewRecords[index].TeamNumber = model.TeamNumber
		exportCashReviewRecords[index].TeamUserName = model.TeamUserName
		exportCashReviewRecords[index].TlNickName = model.TlNickName
		exportCashReviewRecords[index].TeamUserId = model.TeamUserId
		exportCashReviewRecords[index].TlPhone = model.TlPhone
		exportCashReviewRecords[index].TlEmail = model.TlEmail
		exportCashReviewRecords[index].ReviewDesc = model.ReviewDesc
		exportCashReviewRecords[index].AlipayPayTime = ""
		exportCashReviewRecords[index].AlipayOrderNo = ""
		exportCashReviewRecords[index].AlipaySerialNumber = ""
		exportCashReviewRecords[index].PayAccount = ""
		exportCashReviewRecords[index].PayName = ""
		exportCashReviewRecords[index].Amount = ""
		exportCashReviewRecords[index].Status = ""
		exportCashReviewRecords[index].PayRemark = ""
		exportCashReviewRecords[index].FailReason = ""
		exportCashReviewRecords[index].Text = ""
		index++
	}
	unix := time.Now().UnixNano()
	if err := exl.Write(fmt.Sprintf("./export/export_cash_review_records_all_select_%d.xlsx", unix), exportCashReviewRecords); err != nil {
		fmt.Println("write excel err:" + err.Error())
		return
	}
	tempFilename := fmt.Sprintf("./export/export_cash_review_records_all_select_%d.xlsx", unix)
	//删除本地临时文件
	defer os.Remove(tempFilename)
	bucketClient := oss.BucketClient{}
	readFile, _ := ioutil.ReadFile(fmt.Sprintf("./export/export_cash_review_records_all_select_%d.xlsx", unix))
	bucketClient.UpBytes(readFile, fmt.Sprintf("task-assign/order/export/export_cash_review_records_all_select_%d.xlsx", unix))
	ctx.JSON(utils.Response{Code: iris.StatusOK, Message: iris.StatusText(iris.StatusOK), Data: fmt.Sprintf("%s/task-assign/order/export/export_cash_review_records_all_select_%d.xlsx", utils.ServerConf.AliOssConf.CallBackHost, unix)})
	return
}

type BatchDeleteOrderInfoRequest struct {
	Ids []string `json:"ids"`
}

func BatchDeleteOrderInfoHandler(ctx iris.Context) {
	var RequestParams BatchDeleteOrderInfoRequest
	if err := ctx.ReadJSON(&RequestParams); err != nil {
		handler.ArgumentErrorHandle(err, ctx)
		return
	}
	var serve adminServices.SystemOrderService
	if err := serve.BatchDeleteOrderInfo(RequestParams.Ids); err != nil {
		ctx.JSON(utils.ResponseServerError(err))
		return
	} else {
		ctx.JSON(utils.ResponseOK())
		return
	}
}

type ImportProductReview struct {
	OrderId        string `excel:"订单号（必填）"`
	Status         string `excel:"审核是否通过,0表示不通过，1表示通过（必填）"`
	DeliveryTime   string `excel:"发货时间（选填）"`
	TrackingNumber string `excel:"运单号（选填）"`
	SendingCompany string `excel:"寄件公司（选填）"`
	Remark         string `excel:"备注（选填）"`
	ReviewDesc     string `excel:"提示文本（选填）"`
}

func (*ImportProductReview) Configure(rc *exl.ReadConfig) {}
func BatchImportProductReviewResult(ctx iris.Context) {
	_, handle, err := ctx.FormFile("file")
	if err != nil {
		ctx.JSON(utils.ResponseError{Code: iris.StatusInternalServerError, Message: err.Error()})
		return
	}
	file, _ := handle.Open()
	defer file.Close()
	if models, err := exl.Read[*ImportProductReview](file); err != nil {
		fmt.Println("read excel err:" + err.Error())
		ctx.JSON(utils.ResponseServerError(errors.New("excel读取错误")))
		return
	} else {
		var reviewRecordDao dao.Common[dao.SystemOrderReviewRecord]
		var orderServe adminServices.SystemOrderService
		fmt.Printf("read excel num: %d\n", len(models))
		reviewRecordObjs := make([]dao.SystemOrderReviewRecord, len(models))
		index := 0
		for i, model := range models {
			//从第二行开始读取
			if i == 0 {
				continue
			}
			reviewRecordObjs[index].OrderId = model.OrderId
			if status, err := utils.StringToInt(model.Status); err != nil {
				ctx.JSON(utils.ResponseError{Code: iris.StatusInternalServerError, Message: "第[" + utils.IntToString(i+1) + "]行[" + model.Status + "]格式错误"})
				return
			} else {
				if status == 0 {
					//=0按不通过处理
					status = 2
				} else if status == 1 {
					//=1不处理
				} else {
					//其他的按不通过处理
					status = 2
				}
				reviewRecordObjs[index].Status = status
			}
			if utils.StringIsNotEmpty(model.ReviewDesc) {
				reviewRecordObjs[index].ReviewDesc = model.ReviewDesc
			}
			reviewRecordObjs[index].ReviewDetails = fmt.Sprintf("发货时间:%v, 运单号:%v, 寄件公司:%v, 备注:%v", model.DeliveryTime, model.TrackingNumber, model.SendingCompany, model.Remark)
			reviewRecordObjs[index].ReadStatus = 0
			if record, err := reviewRecordDao.First(map[string]interface{}{"order_id": model.OrderId}); err != nil {
				ctx.JSON(utils.ResponseError{Code: iris.StatusInternalServerError, Message: "订单号不存在,请输入正确的订单号!"})
				return
			} else {
				if reviewRecordObjs[index].Status == 2 {
					orderServe.OrderEditRejection(record.OrderId, record.UserId, model.ReviewDesc)
				}
			}
			index++
		}
		if err := orderServe.BatchUpdateOrderReviewRecord(reviewRecordObjs); err != nil {
			ctx.JSON(utils.ResponseServerError(err))
			return
		}
		ctx.JSON(utils.ResponseOK())
		return
	}
}

type ImportCashReview struct {
	OrderId            string `excel:"订单号（必填）"`
	Status             string `excel:"审核是否通过0表示不通过，1表示通过（必填）"`
	AlipayPayTime      string `excel:"支付宝实际支付时间（选填）"`
	AlipayOrderNo      string `excel:"支付宝订单号（选填）"`
	AlipaySerialNumber string `excel:"支付宝流水号（选填）"`
	PayAccount         string `excel:"收款账号（选填）"`
	PayName            string `excel:"姓名（选填）"`
	Amount             string `excel:"金额（元）（选填）"`
	State              string `excel:"状态（选填）"`
	PayRemark          string `excel:"备注（选填）"`
	FailReason         string `excel:"失败原因（选填）"`
	ReviewDesc         string `excel:"提示文本（选填）"`
}

func (*ImportCashReview) Configure(rc *exl.ReadConfig) {}
func BatchImportCashReviewResult(ctx iris.Context) {
	_, handle, err := ctx.FormFile("file")
	if err != nil {
		ctx.JSON(utils.ResponseError{Code: iris.StatusInternalServerError, Message: err.Error()})
		return
	}
	file, _ := handle.Open()
	defer file.Close()
	if models, err := exl.Read[*ImportCashReview](file); err != nil {
		fmt.Println("read excel err:" + err.Error())
		ctx.JSON(utils.ResponseServerError(errors.New("excel读取错误")))
		return
	} else {
		var reviewRecordDao dao.Common[dao.SystemOrderReviewRecord]
		var orderServe adminServices.SystemOrderService
		fmt.Printf("read excel num: %d\n", len(models))
		var reviewRecordObjs []dao.SystemOrderReviewRecord
		index := 0
		for i, model := range models {
			//从第二行开始读取
			if i == 0 {
				continue
			}
			//订单号不为空才导入
			if utils.StringIsNotEmpty(model.OrderId) {
				var reviewRecordObj dao.SystemOrderReviewRecord
				reviewRecordObj.OrderId = model.OrderId
				if status, err := utils.StringToInt(model.Status); err != nil {
					ctx.JSON(utils.ResponseError{Code: iris.StatusInternalServerError, Message: "第[" + utils.IntToString(i+1) + "]行[" + model.Status + "]格式错误"})
					return
				} else {
					if status == 0 {
						//=0按不通过处理
						status = 2
					} else if status == 1 {
						//=1不处理
					} else {
						//其他的按不通过处理
						status = 2
					}
					reviewRecordObj.Status = status
				}
				if utils.StringIsNotEmpty(model.ReviewDesc) {
					reviewRecordObj.ReviewDesc = model.ReviewDesc
				}
				reviewRecordObj.ReviewDetails = fmt.Sprintf("支付宝实际支付时间:%v, 支付宝订单号:%v, 支付宝流水号:%v, 收款账号:%v, 姓名:%v, 金额（元）:%v, 状态:%v, 备注:%v, 失败原因:%v", model.AlipayPayTime, model.AlipayOrderNo, model.AlipaySerialNumber, model.PayAccount, model.PayName, model.Amount, model.State, model.PayRemark, model.FailReason)
				reviewRecordObj.ReadStatus = 0
				reviewRecordObjs = append(reviewRecordObjs, reviewRecordObj)
				if record, err := reviewRecordDao.First(map[string]interface{}{"order_id": model.OrderId}); err != nil {
					ctx.JSON(utils.ResponseError{Code: iris.StatusInternalServerError, Message: "订单号不存在,请输入正确的订单号!"})
					return
				} else {
					if reviewRecordObj.Status == 2 {
						orderServe.OrderEditRejection(record.OrderId, record.UserId, model.ReviewDesc)
					}
				}
				index++
			}
		}
		if err := orderServe.BatchUpdateOrderReviewRecord(reviewRecordObjs); err != nil {
			ctx.JSON(utils.ResponseServerError(err))
			return
		}
		ctx.JSON(utils.ResponseOK())
		return
	}
}
